package com.Dao;

import com.bean.Article;
import com.bean.Remark;
import com.tools.DButil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class RemarkDao {
    //添加评论
    public void addRemark(Remark remark)throws SQLException {
        String sql="insert into remark(author,pubtime,content,recontent,articleId) value(?,?,?,?,?)";
        QueryRunner runner=new QueryRunner(DButil.getDataSource());
        runner.update(sql,remark.getAuthor(),remark.getPubtime(),remark.getContent(),remark.getRecontent(),remark.getArticleId());
    }

    //删除评论
    public void deleteRemark(int id) throws SQLException {
        String sql="delete from remark where id=?";
        QueryRunner runner=new QueryRunner(DButil.getDataSource());
        runner.update(sql,id);
    }

    //显示所有评论
    public List<Remark> getAllRemark() throws SQLException {
        String sql = "select * from remark order by pubtime desc";//根据时间降序，limit0，10——是指分页，10个数据一页
        QueryRunner runner = new QueryRunner(DButil.getDataSource());
        return runner.query(sql, new BeanListHandler<Remark>(Remark.class));
    }

    //获取评论的发布时间
    public Date findPubTime(String content) throws SQLException {
        String sql="select pubtime from remark where content=?";
        QueryRunner runner=new QueryRunner(DButil.getDataSource());
        Date time= (Date) runner.query(sql,new ScalarHandler(),content);
        return time;

    }
    //查询单篇文章下的所有评论
    public static List<Remark> queryRemark(int articleid) throws SQLException {
        List list = new ArrayList();
        String sql = "select * from remark where articleid=" + articleid + " order by pubtime DESC";
        Remark remark = null;
        QueryRunner runner = new QueryRunner(DButil.getDataSource());
        List<Remark> rs = runner.query(sql, new BeanListHandler<Remark>(Remark.class));
        if (rs != null) {
            for (int i = 0; i < rs.size(); i++) {
                remark = new Remark();
                remark.setId(rs.get(i).getId());
                remark.setArticleId(rs.get(i).getArticleId());
                remark.setAuthor(rs.get(i).getAuthor());
                remark.setContent(rs.get(i).getContent());
                remark.setRecontent(rs.get(i).getRecontent());
                remark.setPubtime(rs.get(i).getPubtime());
                remark.setState(rs.get(i).getState());
                list.add(remark);
            }
        }
        return list;
    }
    public int findAllCount(int articleId) throws SQLException {
        String sql="SELECT COUNT(*) FROM remark where articleid=? ";
        QueryRunner runner=new QueryRunner(DButil.getDataSource());
        Long count=(Long) runner.query(sql,new ScalarHandler(),articleId);
        return count.intValue();

    }



}
